<template>
	<a-spin :spinning="spinning">
		<div ref="scollBox" class="max-h-[150px] overflow-y-auto py-3 px-1 scrollbar-thumb" @scroll="scollMore">
			<div v-for="item in showPersons" :key="item.id" class="flex justify-between my-1">
				<div class="mr-2">{{ item.contactsName || '---' }}</div>
				<div>
					手机：
					<a
						@click="
							callPhone(
								item.id,
								detailInfo.customerCode,
								item.contactsPhone,
								detailInfo.customerName,
								detailInfo.followUpStatus
							)
						"
					>
						<PhoneFilled style="transform: rotateY(180deg)" />{{ item.contactsPhone }}
					</a>
				</div>
			</div>
			<div class="text-center">
				<a-spin :spinning="loadingSpinning" size="small" class="mb-[10px]" />
			</div>
		</div>
	</a-spin>
</template>

<script setup>
	import customerApi from '@/api/biz/customerApi'
	import { globalStore } from '@/store'

	const store = globalStore()

	const props = defineProps({
		detailInfo: {
			type: Object,
			default: () => ({})
		},
		type: {
			type: Number,
			required: true
		}
	})
	const emits = defineEmits(['onTransfer'])

	/**
	 * 点击联系人条数获取联系人列表
	 */
	const spinning = ref(false)
	const loadingSpinning = ref(false)
	const showPersons = ref([])
	const personSize = ref(30)
	const getPersonCode = ref('')
	const personTotal = ref(0)
	const getPersons = (code) => {
		if (code) {
			showPersons.value = []
			spinning.value = true
		} else {
			loadingSpinning.value = true
		}

		const getSize = code ? 30 : personSize.value
		const params = {
			customerCode: code ?? getPersonCode.value,
			current: 1,
			size: getSize
		}
		customerApi
			.getPersonList(params)
			.then((res) => {
				spinning.value = false
				loadingSpinning.value = false
				showPersons.value = res.records
				personTotal.value = res.total
				if (code) {
					getPersonCode.value = code
				}
			})
			.catch(() => {
				spinning.value = false
				loadingSpinning.value = false
			})
	}
	const scollBox = ref(null)
	const scollMore = () => {
		if (showPersons.value.length >= personTotal.value) {
			return
		}
		const onBottom = Math.ceil(scollBox.value.scrollTop + scollBox.value.offsetHeight) >= scollBox.value.scrollHeight
		if (onBottom) {
			personSize.value += 10
			getPersons()
		}
	}

	/**
	 * 拨号
	 * @param {*} code customercode
	 * @param {*} id 联系人记录id
	 * @param {*} phone 手机号
	 * @param {*} name 名称
	 * @param {*} status 状态
	 */
	const callPhone = (id, code, phone, name, status) => {
		store.dashboardNode?.open({ id, code, phone, name, type: props.type, status })
		nextTick(() => {
			if (store.dashboardNode?.phoneData.code === code) {
				store.tagIdList = props.detailInfo.tagIdList
				store.tagNameList = props.detailInfo.tagNameList
			}
		})
	}

	const onTransfer = () => {
		emits('onTransfer')
	}

	defineExpose({
		getPersons
	})
</script>

<style scoped></style>
